//
//  WebCell.m
//  WebViewCellDemo
//
//  Created by xiayong on 16/8/31.
//  Copyright © 2016年 bianguo. All rights reserved.
//

#import "WebCell.h"

@interface WebCell ()<WKNavigationDelegate>

@end

@implementation WebCell
-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self)
    {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.scrollV = [[UIScrollView alloc] init];
        self.scrollV.scrollEnabled = NO;
        self.scrollV.showsVerticalScrollIndicator = NO;
        
        [self.contentView addSubview:self.scrollV];

        self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 1)];
        self.webView.navigationDelegate = self;
        self.webView.backgroundColor = [UIColor clearColor];
        self.webView.allowsBackForwardNavigationGestures = YES;
        self.webView.userInteractionEnabled = NO;
        self.webView.scrollView.scrollEnabled = NO;
        self.webView.scrollView.showsVerticalScrollIndicator = NO;
        [self.scrollV addSubview:self.webView];
    }
    return self;
}

- (void)setHtmlUrl:(NSString *)htmlUrl
{
    NSURL *url = [NSURL URLWithString:htmlUrl];
    [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
}


-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
//    hud = [[MBProgressHUD alloc] init];
//    [hud show:YES];
//    [kKeyWindow addSubview:hud];
//    [hud hide:YES afterDelay:8];
}

-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
//    [hud hide:YES];
    @KWeakObj(self)
    [webView evaluateJavaScript:@"document.getElementById(\"id\").scrollHeight;" completionHandler:^(id Result, NSError * error) {
        CGFloat fittingSize = [Result doubleValue];
        selfWeak.scrollV.frame = CGRectMake(0, 0, KSCREENWIDTH, fittingSize + 10);
        selfWeak.webView.frame = CGRectMake(0, 0, KSCREENWIDTH, fittingSize);
        if (selfWeak.webCellReturnHeightBlock)
        {
            selfWeak.webCellReturnHeightBlock(selfWeak, fittingSize + 10);
        }
    }];
}
-(WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
    if (!navigationAction.targetFrame.isMainFrame)
    {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}




@end
